package com.general.framework.wukong.blockingQueue.interview;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

public class ArrayBlockingQueueDemoByCountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        CountDownLatch latch = new CountDownLatch(10);
        Interviewer1 interviewer = new Interviewer1(queue, latch);
        Interviewee1 interviewee = new Interviewee1(queue, latch);
        new Thread(interviewer).start();
        new Thread(interviewee).start();
        latch.await();
    }
}

class Interviewer1 implements Runnable {
    private final BlockingQueue<String> queue;
    private final CountDownLatch latch;

    public Interviewer1(BlockingQueue<String> queue, CountDownLatch latch) {
        this.queue = queue;
        this.latch = latch;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            String candidate = "Candidate" + i;
            try {
                queue.put(candidate);
                System.out.println("已安排好了第 " + candidate + " 位候选者");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    }
}

class Interviewee1 implements Runnable {
    private final BlockingQueue<String> queue;
    private final CountDownLatch latch;

    public Interviewee1(BlockingQueue<String> queue, CountDownLatch latch) {
        this.queue = queue;
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            while (latch.getCount() > 0) {
                String candidate = queue.take();
                System.out.println("第 " + candidate + " 位候选者面试完毕");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}